#!/usr/bin/env python2.2

import getopt
import random
import sys
import warnings

import scrod
import cprdsp_fin

def build_cmdid(row, col, ch, win, event):
    return 0

def log_packet(fp, pkt):
    try:
        fp.write('\n'.join(map(hex, pkt)))
        fp.write('\n')
    except TypeError:
        for w in pkt:
            try:
                hex(w)
            except TypeError:
                msg = "Can't convert" + str(w) + "to hex"
                raise TypeError(msg)


def main():
    """
    send-random-packets.py [opts] 

    Send packets of various lengths with randomized data and see what returns.
    Ideally the DSP_FIN will be hooked up to a SCROD on the inner transceiver
    so it is operating in loopback mode.

    Options:
    ---------------------------------------------------------
      -h              print this message
      -o PATH         write sent packet data to PATH
      -n N            send N packets of each length
      -r LO:HI:STEP   send packets of a range of lengths defined by LO, HI, and
                      STEP
    """

    optl, args = getopt.getopt(sys.argv[1:], "ho:n:r:")
    
    optd = dict(optl)

    if '-h' in optd:
        sys.stderr.write(main.__doc__ + '\n')
        
        sys.stderr.flush()
        return -101

    if '-n' in optd:
        optd['-n'] = int(optd['-n'])
    else:
        optd['-n'] = 10

    if '-r' in optd:
        optd['-r'] = map(int, optd['-r'].split(':'))
    else:
        optd['-r'] = (10, 100, 10)

    if '-o' not in optd:
        optd['-o'] = 'sent-packets-rev1b.txt'

    slots = 'a'
    warnings.warn("Currently hardcoded to talk to `a:0'")

    fplog = open(optd['-o'], 'w')

    lengths  = range(*optd['-r'])
    npkts = len(lengths) * optd['-n']    
    
    nwords_sent = 0
    for i in xrange(len(lengths)):        
        for j in xrange(optd['-n']):
            i_send = i*optd['-n'] + j

            if i_send % 10 == 0:
                sys.stdout.write("%d/%d packets (%d words, %d bytes) sent\r" % 
                                 (i_send, npkts, nwords_sent, nwords_sent*4))
                sys.stdout.flush()

            packet = [random.randrange(0, 200000000, 1)
                      for k in xrange(lengths[i])]

            nwords_sent += len(packet)

            log_packet(fplog, packet)
            cprdsp_fin.send_packets(slots, [packet])
                
    fplog.close()
    
    print "%d/%d packets (%d words, %d bytes) sent" % (npkts, npkts, 
                                                       nwords_sent,
                                                       nwords_sent*4)


if __name__ == "__main__":
    sys.exit(main())
